#!/usr/bin/env python3
"""
验证ChromaDB路径配置问题
检查数据创建和搜索时使用的实际路径
"""

import os
import sys
import asyncio
from pathlib import Path

# 添加src目录到Python路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))

from config import load_config
from database.manager import DatabaseManager
from database.chromadb_client import ChromaDBClient

async def verify_chromadb_paths():
    """验证ChromaDB路径配置"""
    print("=== ChromaDB路径验证 ===")
    
    # 1. 检查当前工作目录
    current_dir = os.getcwd()
    print(f"当前工作目录: {current_dir}")
    
    # 2. 加载配置
    config_dir = os.path.join(os.path.dirname(__file__), 'config')
    config = load_config(config_dir)
    chromadb_config = config.get('databases', {}).get('chromadb', {})
    
    persist_directory = chromadb_config.get('persist_directory', './data/chroma_db')
    print(f"配置中的persist_directory: {persist_directory}")
    
    # 3. 计算绝对路径
    if os.path.isabs(persist_directory):
        abs_path = persist_directory
    else:
        abs_path = os.path.abspath(persist_directory)
    
    print(f"计算出的绝对路径: {abs_path}")
    print(f"该路径是否存在: {os.path.exists(abs_path)}")
    
    if os.path.exists(abs_path):
        contents = os.listdir(abs_path)
        print(f"目录内容数量: {len(contents)}")
        if contents:
            print(f"前5个项目: {contents[:5]}")
    
    # 4. 检查其他可能的ChromaDB路径
    possible_paths = [
        os.path.join(current_dir, 'data', 'chroma_db'),
        os.path.join(current_dir, 'src', 'chroma_db'),
        os.path.join(os.path.dirname(__file__), 'data', 'chroma_db'),
        os.path.join(os.path.dirname(__file__), 'src', 'chroma_db')
    ]
    
    print("\n=== 检查可能的ChromaDB路径 ===")
    for path in possible_paths:
        exists = os.path.exists(path)
        if exists:
            contents = os.listdir(path)
            print(f"✓ {path} (存在, {len(contents)}个项目)")
        else:
            print(f"✗ {path} (不存在)")
    
    # 5. 初始化数据库管理器并检查实际使用的路径
    print("\n=== 初始化ChromaDB客户端 ===")
    try:
        db_manager = DatabaseManager(config)
        await db_manager.initialize()
        
        if hasattr(db_manager.chromadb_client, 'client') and db_manager.chromadb_client.client:
            # 尝试获取ChromaDB客户端的实际路径
            client = db_manager.chromadb_client.client
            if hasattr(client, '_settings') and hasattr(client._settings, 'persist_directory'):
                actual_path = client._settings.persist_directory
                print(f"ChromaDB客户端实际使用的路径: {actual_path}")
            else:
                print("无法获取ChromaDB客户端的实际路径")
            
            # 检查conversations集合
            try:
                conversations_collection = db_manager.chromadb_client.get_collection('conversations')
                if conversations_collection:
                    count = conversations_collection.count()
                    print(f"conversations集合文档数量: {count}")
                else:
                    print("conversations集合不存在")
            except Exception as e:
                print(f"检查conversations集合时出错: {e}")
        
        await db_manager.close()
        
    except Exception as e:
        print(f"初始化数据库管理器时出错: {e}")
    
    # 6. 检查MCP运行时的工作目录
    print("\n=== MCP配置分析 ===")
    print("根据用户提供的MCP配置:")
    print("- command: python")
    print("- args: [\"-u\", \"-m\", \"mcp.main\", \"--stdio\", \"--config\", \"d:\\MCP\\mcp2\\config\"]")
    print("- PYTHONPATH: d:\\MCP\\mcp2\\src")
    print("")
    print("分析:")
    print("- MCP进程的工作目录可能是d:\\MCP\\mcp2")
    print("- 相对路径./data/chroma_db会解析为d:\\MCP\\mcp2\\data\\chroma_db")
    print("- 这与我们发现的有数据的目录一致")

if __name__ == "__main__":
    asyncio.run(verify_chromadb_paths())